package mrusanov.season

import mrusanov.tournament._
import mrusanov.team.Team
import mrusanov.calendar.SeasonCalendar
import java.util.Date
import mrusanov.nation.World

class WorldSeason(val world:World, val year:Int, val nationSeasons:Vector[NationSeason]) {
  private val internationalChampsEnabled = false

  val goldenLeague = if (internationalChampsEnabled) Some(buildGoldenLeague)
                     else None
  val silverLeague = if (internationalChampsEnabled) Some (buildSilverLeague)
                     else None

  val nationsSeasonsMap = nationSeasons.map(s => (s.nation, s)).toMap
  val calendar = new SeasonCalendar(year)

  private def buildGoldenLeague:Tournament = {
    val dates = calendar.datesOfWorldCup
    val groupRound = new RoundRobinTournamentRound(32, 8, 2, 2, dates.slice(0, 6))
    val oneEights = new KnockOutTournamentRound(16, 2, dates.slice(6, 8))
    val quarter = new KnockOutTournamentRound(8, 2, dates.slice(8, 10))
    val half = new KnockOutTournamentRound(4, 2, dates.slice(10, 12))
    val finalGame = new KnockOutTournamentRound(2, 1, dates.slice(12, 13))

    new Tournament("", Vector(groupRound, oneEights, quarter, half, finalGame))
  }

  private def buildSilverLeague:Tournament = {
    val dates = calendar.datesOfWorldCup
    val firstRound = new KnockOutTournamentRound(128, 2, dates.slice(0, 2))
    val secondRound = new KnockOutTournamentRound(64, 2, dates.slice(2, 4))
    val thirdRound = new KnockOutTournamentRound(32, 2, dates.slice(4, 6))
    val oneEights = new KnockOutTournamentRound(16, 2, dates.slice(6, 8))
    val quarter = new KnockOutTournamentRound(8, 2, dates.slice(8, 10))
    val half = new KnockOutTournamentRound(4, 2, dates.slice(10, 12))
    val finalGame = new KnockOutTournamentRound(2, 1, dates.slice(12, 13))

    new Tournament("", Vector(firstRound,secondRound, thirdRound, oneEights, quarter, half, finalGame))
  }

  def dateGames(date:Date):List[MatchInfo] = {
    val goldenMatches = goldenLeague.map(_.matchesByDate(date)).getOrElse(Nil)
    val silverMatches = silverLeague.map(_.matchesByDate(date)).getOrElse(Nil)

    val nationalMatches = nationSeasons.map(_.matchesByDate(date)).flatten
    goldenMatches ++ silverMatches ++ nationalMatches
  }

  def teamsGames(team:Team):Vector[MatchInfo] = {
    val nationSeason = nationsSeasonsMap(team.club.nation)
    Vector(goldenLeague, silverLeague, Some(nationSeason.nationalCup), Some(nationSeason.league(team))).
      flatten.flatMap(_.teamMatches(team))
  }
}
